<template>
  <div class="flex overflow-hidden h-full">
    <!-- 侧边栏：历史会话 -->
    <div
      class="w-64 border-r bg-white flex-shrink-0 overflow-y-auto"
      style="height: calc(75vh - 0px); padding: 16px"
      @scroll="handleSessionScroll"
      ref="sessionListRef"
    >
      <h2 class="text-base font-bold mb-2">历史会话</h2>
      <ul>
        <li
          v-for="item in sessionOptions"
          :key="item.value"
          :class="[
            'cursor-pointer px-2 py-1 rounded',
            sessionId === item.value ? 'bg-blue-100 text-blue-600' : 'hover:bg-gray-100'
          ]"
          @click="loadSession(item.value)"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>

    <!-- 主窗口：聊天区域，继承高度 -->
    <div class="flex-1 relative overflow-hidden h-full">
      <!-- 平台选择和按钮 -->
      <div class="p-4 flex items-center space-x-4 bg-white">
        <el-select
          v-model="selectedPlatform"
          placeholder="请选择使用的AI平台"
          style="width: 260px"
          @change="handlePlatformChange"
          filterable
          clearable
        >
          <el-option
            v-for="item in platformOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="startNewSession">+ 新建对话</el-button>
      </div>

      <!-- 聊天记录区域 -->
      <div
        ref="scrollRef"
        class="absolute inset-x-4 overflow-y-auto bg-gray-50 p-4 text-sm"
        :style="{ top: '72px', bottom: '60px' }"
      >
        <div
          v-for="(msg, index) in chatHistory"
          :key="index"
          :class="{ 'text-right': msg.role === 'user', 'text-left': msg.role === 'assistant' }"
        >
          <p>
            <b>{{ msg.role === 'user' ? '你' : 'AI' }}:</b>
            {{ msg.content }}
          </p>
        </div>
        <div v-if="loading" class="text-gray-400 animate-pulse">AI正在输入中...</div>
      </div>

      <!-- 输入框 -->
      <div class="absolute inset-x-4 bottom-0 p-4 bg-white flex items-center space-x-2">
        <el-input
          v-model="input"
          placeholder="输入问题回话，按 Enter 或 发送"
          @keydown.enter="handleSend"
          clearable
          class="flex-1"
        />
        <el-button type="primary" :loading="loading" @click="handleSend">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getPlatformsApi,
  streamChatApi,
  saveMessageApi,
  getMessagesApi,
  getSessionPageApi,
  saveSessionApi,
  getIsStreamApi,
  chatWithAiApi
} from '@/api/ai'

const input = ref('')
const selectedPlatform = ref('')
const sessionOptions = ref<{ label: string; value: string; platform: string }[]>([])
const chatHistory = ref<{ role: string; content: string }[]>([])
const platformOptions = ref<{ label: string; value: string }[]>([])
const sessionId = ref(`sess-${Date.now()}`)
const loading = ref(false)
const scrollRef = ref<HTMLElement>()
const sessionListRef = ref<HTMLElement>()
const persistedSessionIds = ref<string[]>([])

const currentSessionPage = ref(1)
const pageSize = 20
const sessionListFinished = ref(false)
const isStream = ref(true)

const loadSessions = async () => {
  if (sessionListFinished.value) return
  try {
    const res = await getSessionPageApi(currentSessionPage.value, pageSize)
    if (res?.success && res.result) {
      const records = res.result.records || []
      if (records.length < pageSize) sessionListFinished.value = true

      const newSessions = records.map((item: any) => ({
        label: item.title,
        value: item.sessionId,
        platform: item.platform
      }))
      sessionOptions.value.push(...newSessions)
      currentSessionPage.value++
    } else {
      ElMessage.error('加载会话列表失败')
    }
  } catch (error) {
    console.error('加载会话失败：', error)
    ElMessage.error('请求异常，无法加载会话')
  }
}

const handleSessionScroll = () => {
  const el = sessionListRef.value
  if (!el) return
  const threshold = 40
  if (el.scrollTop + el.clientHeight + threshold >= el.scrollHeight) {
    loadSessions()
  }
}

// const handleSend = async () => {
//   if (!input.value || !selectedPlatform.value || !sessionId.value) return

//   const userMessage = input.value
//   chatHistory.value.push({ role: 'user', content: userMessage })

//   await saveMessageApi({
//     sessionId: sessionId.value,
//     role: 'user',
//     content: userMessage,
//     platform: selectedPlatform.value
//   })

//   if (!persistedSessionIds.value.includes(sessionId.value)) {
//     const label = userMessage.slice(0, 20) || '新会话'
//     await saveSessionApi({
//       sessionId: sessionId.value,
//       title: label,
//       platform: selectedPlatform.value
//     })
//     persistedSessionIds.value.push(sessionId.value)
//   }

//   input.value = ''
//   loading.value = true
//   let aiContent = ''
//   const assistantIndex = chatHistory.value.length
//   chatHistory.value.push({ role: 'assistant', content: '' })

//   try {
//     const messages = chatHistory.value.map((msg) => ({
//       role: msg.role,
//       content: msg.content
//     }))

//     const eventSource = streamChatApi({
//       platform: selectedPlatform.value,
//       sessionId: sessionId.value,
//       messages
//     })

//     eventSource.onmessage = (event) => {
//       if (event.data === '[DONE]') {
//         eventSource.close()
//         loading.value = false
//         if (aiContent.trim()) {
//           saveMessageApi({
//             sessionId: sessionId.value,
//             role: 'assistant',
//             content: aiContent,
//             platform: selectedPlatform.value
//           })
//         }
//         return
//       }

//       const clean = event.data?.replace(/^data:\s*/, '').trim()
//       if (clean) {
//         aiContent += clean
//         chatHistory.value[assistantIndex].content = aiContent

//         nextTick(() => {
//           if (scrollRef.value) {
//             scrollRef.value.scrollTop = scrollRef.value.scrollHeight
//           }
//         })
//       }
//     }

//     eventSource.onerror = (e) => {
//       console.warn('SSE 连接出错:', e)
//       if (!aiContent) {
//         ElMessage.error('AI流式请求失败或中断')
//       }
//       eventSource.close()
//       loading.value = false
//     }
//   } catch (e) {
//     ElMessage.error('AI请求异常')
//     loading.value = false
//   }
// }
const handleSend = async () => {
  if (!input.value || !selectedPlatform.value || !sessionId.value) return

  const userMessage = input.value
  chatHistory.value.push({ role: 'user', content: userMessage })

  await saveMessageApi({
    sessionId: sessionId.value,
    role: 'user',
    content: userMessage,
    platform: selectedPlatform.value
  })

  if (!persistedSessionIds.value.includes(sessionId.value)) {
    const label = userMessage.slice(0, 20) || '新会话'
    await saveSessionApi({
      sessionId: sessionId.value,
      title: label,
      platform: selectedPlatform.value
    })
    persistedSessionIds.value.push(sessionId.value)
  }

  input.value = ''
  loading.value = true
  const assistantIndex = chatHistory.value.length
  chatHistory.value.push({ role: 'assistant', content: '' })
  console.log('asdasd')
  try {
    // ✅ 获取是否为流式
    const res = await getIsStreamApi(selectedPlatform.value)
    console.log('asdasd', res)
    isStream.value = res.success && res.result

    const messages = chatHistory.value.map((msg) => ({
      role: msg.role,
      content: msg.content
    }))

    if (isStream.value) {
      // 🔁 流式逻辑
      let aiContent = ''
      const eventSource = streamChatApi({
        platform: selectedPlatform.value,
        sessionId: sessionId.value,
        messages
      })

      eventSource.onmessage = (event) => {
        if (event.data === '[DONE]') {
          eventSource.close()
          loading.value = false
          if (aiContent.trim()) {
            saveMessageApi({
              sessionId: sessionId.value,
              role: 'assistant',
              content: aiContent,
              platform: selectedPlatform.value
            })
          }
          return
        }

        const clean = event.data?.replace(/^data:\s*/, '').trim()
        if (clean) {
          aiContent += clean
          chatHistory.value[assistantIndex].content = aiContent

          nextTick(() => {
            scrollRef.value!.scrollTop = scrollRef.value!.scrollHeight
          })
        }
      }

      eventSource.onerror = (e) => {
        console.warn('SSE 连接出错:', e)
        eventSource.close()
        loading.value = false
      }
    } else {
      // 🧊 非流式逻辑
      const res = await chatWithAiApi({
        platform: selectedPlatform.value,
        sessionId: sessionId.value,
        prompt: userMessage
      })
      if (res.success) {
        const aiReply = res.result
        chatHistory.value[assistantIndex].content = aiReply
        await saveMessageApi({
          sessionId: sessionId.value,
          role: 'assistant',
          content: aiReply,
          platform: selectedPlatform.value
        })
      }
      loading.value = false
      nextTick(() => {
        scrollRef.value!.scrollTop = scrollRef.value!.scrollHeight
      })
    }
  } catch (e) {
    ElMessage.error('AI请求异常')
    loading.value = false
  }
}

const startNewSession = () => {
  const userFirstMsg = chatHistory.value.find((msg) => msg.role === 'user')?.content?.trim()

  if (userFirstMsg) {
    const label = userFirstMsg.slice(0, 20)
    sessionOptions.value = [
      {
        label,
        value: sessionId.value,
        platform: selectedPlatform.value
      },
      ...sessionOptions.value.filter((s) => s.value !== sessionId.value)
    ]
    saveSessionApi({
      sessionId: sessionId.value,
      title: label,
      platform: selectedPlatform.value
    })
  }

  sessionId.value = `sess-${Date.now()}`
  chatHistory.value = []

  sessionOptions.value = [
    {
      label: '当前会话',
      value: sessionId.value,
      platform: selectedPlatform.value
    },
    ...sessionOptions.value.filter((s) => s.value !== sessionId.value)
  ]
}

const handlePlatformChange = (val: string) => {
  if (!sessionOptions.value.some((s) => s.value === sessionId.value)) {
    sessionOptions.value.unshift({ label: '新会话', value: sessionId.value, platform: val })
  }
}

const loadSession = async (id: string) => {
  try {
    const res = await getMessagesApi(id)
    const messages = res?.result?.records ?? []
    if (res.success && Array.isArray(messages)) {
      chatHistory.value = messages.filter((msg) => ['user', 'assistant'].includes(msg.role))

      const session = sessionOptions.value.find((item) => item.value === id)
      if (session) {
        selectedPlatform.value = session.platform
        sessionId.value = session.value
      }

      nextTick(() => {
        if (scrollRef.value) {
          scrollRef.value.scrollTop = scrollRef.value.scrollHeight
        }
      })
    } else {
      ElMessage.error('加载聊天记录失败')
    }
  } catch (e) {
    console.error('加载历史出错：', e)
    ElMessage.error('加载历史消息异常')
  }
}

onMounted(() => {
  getPlatformsApi().then((res) => {
    if (res.success) {
      platformOptions.value = res.result.map((item: string) => ({ label: item, value: item }))
      if (!selectedPlatform.value && platformOptions.value.length > 0) {
        selectedPlatform.value = platformOptions.value[0].value
      }
    }
  })

  sessionOptions.value.push({
    label: '当前会话',
    value: sessionId.value,
    platform: selectedPlatform.value
  })

  loadSessions()
})
</script>
